import 'package:flutter/material.dart';

class EnhancedCarouselDialog extends StatefulWidget {
  final int initialIndex;

  const EnhancedCarouselDialog({super.key, this.initialIndex = 0});

  @override
  State<EnhancedCarouselDialog> createState() => _EnhancedCarouselDialogState();
}

class _EnhancedCarouselDialogState extends State<EnhancedCarouselDialog> {
  late PageController _pageController;
  late int _currentIndex;
  late ScrollController _thumbnailScrollController;

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex;
    _pageController = PageController(initialPage: _currentIndex);
    _thumbnailScrollController = ScrollController();
  }

  @override
  void dispose() {
    _pageController.dispose();
    _thumbnailScrollController.dispose();
    super.dispose();
  }

  // 滚动到选中的缩略图位置
  void _scrollToThumbnail(int index) {
    // 确保缩略图列表已经渲染完成
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final double position = index * 95.0; // 95 = 缩略图高度(80) + 间距(15)
      final maxScroll = _thumbnailScrollController.position.maxScrollExtent;
      final double scrollPosition = position.clamp(0.0, maxScroll);

      _thumbnailScrollController.animateTo(
        scrollPosition,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    });
  }

  void _onThumbnailTap(int index) {
    setState(() {
      _currentIndex = index;
      _pageController.animateToPage(
        index,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    });
    _scrollToThumbnail(index);
  }

  void _onPageChanged(int index) {
    setState(() {
      _currentIndex = index;
    });
    _scrollToThumbnail(index);
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.black54,
      insetPadding: const EdgeInsets.all(20),
      child: Container(
        height: MediaQuery
            .of(context)
            .size
            .height * 0.85,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
        ),
        child: Column(
          children: [
            // 主体内容
            Expanded(child: _buildContent()),
          ],
        ),
      ),
    );
  }

  Widget _buildContent() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // 左侧缩略图列表
        _buildThumbnailList(),
        // 中间轮播大图
        Expanded(child: _buildCarousel()),
        // 右侧旋转标题
        _buildRotatedTitle(),
      ],
    );
  }

  Widget _buildThumbnailList() {
    final thumbnails = List.generate(8, (index) {
      return Container(
        color: _getThumbnailColor(index),
        child: Center(
          child: Text(
            '图${index + 1}',
            style: const TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
      );
    });
    double itemH = 75;
    double itemW = 58;
    return Container(
      color: Colors.pink,
      width: itemH,  // 列表总宽度保持不变
      // margin: const EdgeInsets.only(top: 10, bottom: 20, left: 12),
      child: NotificationListener<ScrollNotification>(
        onNotification: (notification) => true,
        child: Scrollbar(
          controller: _thumbnailScrollController,
          child: ListView.builder(
            controller: _thumbnailScrollController,
            itemCount: thumbnails.length,
            itemBuilder: (context, index) {
              final isSelected = _currentIndex == index;
              return GestureDetector(
                onTap: () => _onThumbnailTap(index),
                child: Center(
                  child: ConstrainedBox( // 解决方案核心
                    constraints: BoxConstraints(
                      maxWidth: isSelected ? itemW : 48,
                      maxHeight: isSelected ? itemH : 64,
                    ),
                    child: Container(
                      // duration: const Duration(milliseconds: 300),
                      // curve: Curves.easeInOut,
                      width: isSelected ? itemW : 48,
                      height: isSelected ? itemH : 64,
                      margin: const EdgeInsets.only(bottom: 8),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(4),
                        border: Border.all(
                          color: isSelected ? Colors.white : Colors.grey,
                          width: isSelected ? 2 : 0,
                        ),
                        boxShadow: isSelected
                            ? [
                          BoxShadow(
                            color: Colors.blue.withOpacity(0.3),
                            blurRadius: 8,
                            spreadRadius: 1,
                          ),
                        ] : [],
                      ),
                      child: thumbnails[index],
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  final colors = [
    Colors.blue.shade100,
    Colors.green.shade100,
    Colors.orange.shade100,
    Colors.purple.shade100,
    Colors.red.shade100,
    Colors.teal.shade100,
    Colors.yellow.shade100,
    Colors.deepOrange.shade100,
  ];

  // 根据索引返回不同的缩略图背景色
  Color _getThumbnailColor(int index) {
    return colors[index % colors.length];
  }

  Widget _buildCarousel() {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 12),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[300]!),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: PageView.builder(
          controller: _pageController,
          scrollDirection: Axis.vertical,
          onPageChanged: _onPageChanged,
          itemCount: colors.length,
          itemBuilder: (context, index) {
            return AnimatedSwitcher(
              duration: const Duration(milliseconds: 300),
              child: Container(
                key: ValueKey<int>(index),
                color: Colors.grey[200],
                child: Stack(
                  children: [
                    Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            width: 200,
                            height: 200,
                            color: _getThumbnailColor(index),
                          ),
                        ],
                      ),
                    ),
                    // _buildImageAnnotations(index),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildRotatedTitle() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        SizedBox(width: 20),
        Container(
          width: 40,
          margin: const EdgeInsets.only(right: 16),
          padding: const EdgeInsets.only(top: 40, bottom: 20),
          child: RotatedBox(
            quarterTurns: 1,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '客厅样例',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
              ],
            ),
          ),
        ),
        IconButton(
          icon: const Icon(Icons.close),
          onPressed: () => Navigator.pop(context),
        ),
      ],
    );
  }
}
